package com.cars.elasticsearch.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cars.elasticsearch.domain.DO.Files;
import com.cars.elasticsearch.mapper.FileMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author: caoqianfan
 * @date: 2023/10/12 16:24
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Value("${server.port}")
    private String port;

    @Value("${server.address}")
    private String ip;

    @Resource
    private FileMapper fileMapper;

    //上传
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //文件名.jpg
        String type = FileUtil.extName(originalFilename);//.jpg
        long size = file.getSize();//大小

        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type; //41b1076684904f9cb4a503fb028db94b.jpg
        File uploadFile = new File(fileUploadPath + fileUUID);
        //先存储到磁盘
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        String url;
        file.transferTo(uploadFile);
        //获取文件的md5
        //使用m5 避免重复上传相同的文件
        String md5 = SecureUtil.md5(uploadFile);
        Files dbFiles = getFileByMD5(md5);
        if (dbFiles != null) {
            url = dbFiles.getUrl();
            uploadFile.delete();
        } else {
            url = "http://" + ip + ":" + port + "/file/" + fileUUID;
        }
        //保存到数据库
        Files saveFiles = new Files();
        saveFiles.setName(originalFilename);
        saveFiles.setType(type);
        saveFiles.setSize(size / 1024);
        saveFiles.setUrl(url);
        saveFiles.setMd5(md5);
        fileMapper.insert(saveFiles);
        return url;

    }

    //下载
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID,
                         HttpServletResponse response) throws IOException {

        java.io.File uploadFile = new java.io.File(fileUploadPath + fileUUID);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, StandardCharsets.UTF_8));
        response.setContentType("application/octet-stream");

        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

    public Files getFileByMD5(String md5) {
        QueryWrapper<Files> wrapper = new QueryWrapper<>();
        wrapper.eq("md5", md5);
        List<Files> filesList = fileMapper.selectList(wrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    }
}